<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 2017/4/9
 * Time: 上午10:58
 */

namespace app\admin\controller;
use app\admin\model;
use think\Db;

class AdminMenu extends Admin
{
    /**
     * 自定义模版前缀
     * @var string
     */
    protected $templatePrefix = 'admin/menu/';

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new model\AdminMenu();
    }

    /**
     * 列表
     * @return mixed
     */
    public function index()
    {
        $pid = input('param.pid', 0);

        $parentInfo = [];
        if (!empty($pid)) {
            $parentInfo = $this->model->get($pid);
        }

        $list = $this->model->where('status', '>=', 0)->where('pid', '=', $pid)->order('sort', 'ASC')->order('id', 'DESC')->select();

        //  上一个页面地址
        $prevUrl = cookie('__forward__');

        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->fetch('index', ['list'=>$list, 'parentInfo'=>$parentInfo, 'pid'=>$pid]);
    }

    /**
     * 添加菜单页面
     * @return mixed
     */
    public function add()
    {
        $info = $this->model;
        $info->pid = input('param.pid');
        $info->is_dev = 0;
        $info->sort = 0;
        $info->hide = 0;
        $info->menu_type = 2;
        if (empty($info->pid)) {
            $info->root_id = 0;
        } else {
            $root_id = model\AdminMenu::where('id', $info->pid)->value('root_id');
            $info->root_id = $root_id ? $root_id : $info->pid;
        }
        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 更新菜单页面
     * @return mixed
     */
    public function edit()
    {
        $id = input('param.id');

        if (empty($id)) {
            $this->error('缺少必要参数', cookie('__forward__'));
        }
        $info = $this->model->get($id);

        return $this->fetch('edit', ['info'=>$info]);
    }

    /**
     * 保存数据
     */
    public function save()
    {
        if (!request()->isPost()) {
            $this->error('错误的请求方式', cookie('__forward__'));
        }

        $id = input('post.id', 0);

        if (empty($id)) {
            $re = $this->model->data($_POST)->allowField(true)->save();
            if ($re) {
                $id = $this->model->getLastInsID();
            }
            $url = $type = '';
        } else {
            $info = $this->model->find($id);
            $url = $info->url;
            $type = $info->menu_type;
            $re = $this->model->allowField(true)->save($_POST, ['id' => $id]);
        }

        if ($re === false) {
            $this->error('操作失败');
        }

        $this->setAuthRule($id, $url, $type);

        //  清除菜单session 信息
        model\AdminMenu::clearMenuSession();

        $this->success('操作成功', cookie('__forward__'));
    }

    /**
     * 更新状态后执行的方法
     */
    protected function afterSetStatus()
    {
        $ids = input('param.ids', []);
        if (is_array($ids)) {
            $ids = arr2str($ids);
        }
        $this->setAuthRule($ids);

        model\AdminMenu::clearMenuSession();
    }

    /**
     * 删除数据后执行的方法
     */
    protected function afterDelete()
    {
        $ids = input('param.ids', []);
        if (is_array($ids)) {
            $ids = arr2str($ids);
        }
        $this->setAuthRule($ids);

        model\AdminMenu::clearMenuSession();
    }

    /**
     * 同步更新规则表中的数据
     * @param $ids
     * @param string $url
     * @param string $type
     * @return bool
     */
    protected function setAuthRule($ids, $url='', $type='')
    {
        $idArr = str2arr($ids);

        $authRuleModel = new model\AuthRule();


//        $list = $this->model->where('status', 99)->order('id asc')->select();
//        foreach ($list as $key=>$value) {
//            $idArr[] = $value->id;
//        }

        foreach ($idArr as $k=>$id) {
            $info = $this->model->field('title, menu_type, url, status')->find($id);
            if (count($idArr) > 1 || empty($url) || empty($type)) {
                $url = $info->url;
                $type = $info->menu_type;
            }
            $authRuleModel->saveRule([
                'name' => $info->url,
                'type' => $info->menu_type,
                'status' => $info->status,
                'title' => $info->title
            ], $url, $type);
        }

        return true;
    }
}